package vn.allmobile.ambnews.activities.detail;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Tracker;

import vn.allmobile.ambnews.BaseActivity;
import vn.allmobile.ambnews.R;
import vn.allmobile.ambnews.customview.WebviewDetail;
import vn.allmobile.ambnews.data.Article;
import vn.allmobile.ambnews.data.DbFeedAdapter;
import vn.allmobile.ambnews.network.NetworkAPI;
import vn.allmobile.ambnews.utils.Contants;
import vn.allmobile.ambnews.utils.GlobalApplication;
import vn.allmobile.ambnews.utils.Log;
import vn.allmobile.ambnews.utils.PreferenceManager;
import vn.allmobile.ambnews.utils.Utils;

import android.os.Bundle;
import android.os.PowerManager;
import android.content.Intent;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class DetailActivity extends BaseActivity {
	protected WebviewDetail webView;
	public static int _totalPage = 0;
	public static int _currentPage = 0;
	public int _isLoaded = 0;
	public static int _screenWidth;
	public static int _screenHeight;
	public static RelativeLayout loadingPanel;
	static int _isFontChange = 0;
	public static Article article;
	String load_path = "";
	String content = "";
	PowerManager pm;
	PowerManager.WakeLock wakeLock;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_detail);
		NetworkAPI._imageList.clear();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);

		 // Display device width and height in pixels
		int screenHeightpx = dm.heightPixels;
		int screenWidthpx  = dm.widthPixels;
		
		float desity	= dm.density;
		
		_screenHeight = Math.round(screenHeightpx / desity) - 10 ;
		_screenWidth = Math.round(screenWidthpx / desity) ;
		
		ImageView backBtn = (ImageView)findViewById(R.id.backButton);
		backBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				/*if (wakeLock.isHeld())				    
					wakeLock.release();
					*/
				DetailActivity.this.onBackPressed();
				
			}
		});
		loadingPanel = (RelativeLayout)findViewById(R.id.loadingPane);
		
		webView = (WebviewDetail)findViewById(R.id.webview);
		webView.set_activity(this);
		webView.init();
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		String id 		= bundle.getString(Contants.EXTRA_DETAIL_ID);

		article =  DbFeedAdapter.getArticle(id);
		content = article.getContent().trim();
		
		String pp_id = article.getPaperId();
		String slug = NetworkAPI._papersMap.get(pp_id).getSlug();
		String fontsize = PreferenceManager.getfontSize();	
					
		content = content.replaceAll("\\s*[\\r\\n]+\\s*", "");
		content = content.replaceAll("'","\\\\'");
		content = content.replaceAll("\"", "\\\\\"");
		
		Log.v(content);
		
		String css = "";
		if(PreferenceManager.isNightMode())
		{
			css = "html{font-size:"+fontsize+" !important;background:black !important;} *{color:white !important}";
		}
		else
			css = "html{font-size:"+fontsize+" !important} ";
			
		
		
		String tmpl = "<div id=\"templates\" data-ambfl-hash=\"147e60\" data-supports=\"captionOverlay\"><style type=\"text/css\"> " + css +"   .master-footer .logo {  position: absolute;top: 1px;left: 16px;width: 60px;height: 17px;background: url(http://news.allmobile.vn/flip/tmpl/images/"+slug+"/footer-logo.png) transparent top left no-repeat;background-size: 69px 17px    }    body .phone-article-cover-noimage .logo {       margin: 0 0 0 -16px;padding: 0 16px;height: 49px;background: #F7F7F7 url(http://news.allmobile.vn/flip/tmpl/images/"+slug+"/cover-logo.png)  0 0 no-repeat;background-size: auto 100%;    	width:auto;    }</style><div class=\"phone-article-cover-noimage template-phone template-article cover\">    <div class=\"content-frame\"><div class=\"navborder\"></div><header>    <div class=\"logo\"></div>    <div class=\"title\"></div>    <div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;/&nbsp;<span    class=\"pageCount\">6</span></div></header><div class=\"pagecontainer\" name=\"pagecontainer\" align-bottom-to=\"master-footer.top\">    <div class=\"titlecontainer\"><div class=\"logo\"></div><div class=\"rubric\"></div><div class=\"title\"></div><div class=\"creditbox\">    <div class=\"dateline first\"></div>    <div class=\"byline\" hide-if-empty=\"1\"></div>    <div class=\"dateline last\"></div></div>    </div>    <div class=\"column fullwidth frame\" align-bottom-to=\"master-footer.top\"></div></div><div class=\"tester\">phone-article-cover-noimage</div><div class=\"master-footer\" name=\"master-footer\">    <div class=\"footer-spacer\"><div class=\"logo\"></div><div class=\"title\"></div><div class=\"dateline\"></div><div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;<span  class=\"footerof\">/</span>&nbsp;<span  class=\"pageCount\">6</span></div>    </div></div>    </div></div><div class=\"phone-article-tall-text template-phone template-article\">    <div class=\"content-frame\"><div class=\"navborder\"></div><header>    <div class=\"logo\"></div>    <div class=\"title\"></div>    <div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;of&nbsp;<span    class=\"pageCount\">6</span></div></header><div class=\"pagecontainer\" name=\"pagecontainer\" align-bottom-to=\"master-footer.top\">    <div class=\"imagecontainer\"><div class=\"image\"></div><div class=\"captionBody\"></div>    </div>    <div class=\"column fullwidth frame\" align-bottom-to=\"master-footer.top\"></div></div><div class=\"tester\">phone-article-tall-text</div><div class=\"master-footer\" name=\"master-footer\">    <div class=\"footer-spacer\"><div class=\"logo\"></div><div class=\"title\"></div><div class=\"dateline\"></div><div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;<span  class=\"footerof\">/</span>&nbsp;<span  class=\"pageCount\">6</span></div>    </div></div>    </div></div><div class=\"phone-article-text template-phone template-article\">    <div class=\"content-frame\"><div class=\"navborder\"></div><header>    <div class=\"logo\"></div>    <div class=\"title\"></div>    <div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;of&nbsp;<span    class=\"pageCount\">6</span></div></header><div class=\"pagecontainer\" name=\"pagecontainer\" align-bottom-to=\"master-footer.top\">    <div class=\"column fullwidth frame\" align-bottom-to=\"master-footer.top\"></div></div><div class=\"tester\">phone-article-text</div><div class=\"master-footer\" name=\"master-footer\">    <div class=\"footer-spacer\"><div class=\"logo\"></div><div class=\"title\"></div><div class=\"dateline\"></div><div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;<span  class=\"footerof\">/</span>&nbsp;<span  class=\"pageCount\">6</span></div>    </div></div>    </div></div><div class=\"phone-article-wide-text template-phone template-article\">    <div class=\"content-frame\"><div class=\"navborder\"></div><header>    <div class=\"logo\"></div>    <div class=\"title\"></div>    <div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;of&nbsp;<span    class=\"pageCount\">6</span></div></header><div class=\"pagecontainer\" name=\"pagecontainer\" align-bottom-to=\"master-footer.top\">    <div class=\"imagecontainer\"><div class=\"image\"></div><div class=\"captionBody\"></div>    </div>    <div class=\"column fullwidth frame\" align-bottom-to=\"master-footer.top\"></div></div><div class=\"tester\">phone-article-wide-text</div><div class=\"master-footer\" name=\"master-footer\">    <div class=\"footer-spacer\"><div class=\"logo\"></div><div class=\"title\"></div><div class=\"dateline\"></div><div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;<span  class=\"footerof\">/</span>&nbsp;<span  class=\"pageCount\">6</span></div>    </div></div>    </div></div><div class=\"phone-article-tall template-phone template-article\">    <div class=\"content-frame\"><div class=\"navborder\"></div><header>    <div class=\"logo\"></div>    <div class=\"title\"></div>    <div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;of&nbsp;<span    class=\"pageCount\">6</span></div></header><div class=\"pagecontainer\" name=\"pagecontainer\" align-bottom-to=\"master-footer.top\">    <div class=\"imagecontainer\"><div class=\"image\"></div><div class=\"captionBody\"></div>    </div>    <div class=\"column fullwidth frame\" align-bottom-to=\"master-footer.top\"></div></div><div class=\"tester\">phone-article-wide-text</div><div class=\"master-footer\" name=\"master-footer\">    <div class=\"footer-spacer\"><div class=\"logo\"></div><div class=\"title\"></div><div class=\"dateline\"></div><div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;<span  class=\"footerof\">/</span>&nbsp;<span  class=\"pageCount\">6</span></div>    </div></div>    </div></div><div class=\"phone-article-video template-phone template-video \">    <div class=\"content-frame\"><div class=\"navborder\"></div><header>    <div class=\"logo\"></div>    <div class=\"title\"></div>    <div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;of&nbsp;<span    class=\"pageCount\">6</span></div></header><div class=\"pagecontainer\" name=\"pagecontainer\" align-bottom-to=\"master-footer.top\">    <div class=\"video\"></div>    <div class=\"column fullwidth frame\" align-bottom-to=\"master-footer.top\"></div></div><div class=\"tester\">phone-article-video</div><div class=\"master-footer\" name=\"master-footer\">    <div class=\"footer-spacer\"><div class=\"logo\"></div><div class=\"title\"></div><div class=\"dateline\"></div><div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;<span  class=\"footerof\">/</span>&nbsp;<span  class=\"pageCount\">6</span></div>    </div></div>    </div></div><div class=\"phone-article-video-text template-phone template-video \">    <div class=\"content-frame\"><div class=\"navborder\"></div><header>    <div class=\"logo\"></div>    <div class=\"title\"></div>    <div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;/&nbsp;<span    class=\"pageCount\">6</span></div></header><div class=\"pagecontainer\" name=\"pagecontainer\" align-bottom-to=\"master-footer.top\">    <div class=\"column fullwidth frame\" align-bottom-to=\"master-footer.top\"></div></div><div class=\"tester\">phone-article-video</div><div class=\"master-footer\" name=\"master-footer\">    <div class=\"footer-spacer\"><div class=\"logo\"></div><div class=\"title\"></div><div class=\"dateline\"></div><div class=\"footer\">Trang&nbsp;<span class=\"currentPageNumber\">2</span>&nbsp;<span  class=\"footerof\">/</span>&nbsp;<span  class=\"pageCount\">6</span></div>    </div></div> </div></div></div>";				
		//String article_path = "http%3A%2F%2Fnews.allmobile.vn%2F"+ paper +"%2F"+ category +"%2F"+ id +"%2Farticle.html";
		//load_path = "http://news.allmobile.vn/flip/flip.html?formFactor=phone";
		load_path ="file:///android_asset/flip.html";
		//Log.v(article_path);
		//Log.v(load_path);
		this._isLoaded = 0 ;
		////window.ambflipArticleMarkup = '" + content +"';
		webView.loadUrl("javascript:window.ambflipNativeFlip = true;window.isAndroid = true;window.ambflipMagazine = true;window.ambflipBridgeEnabled = true;window.ambflipShowImageEnabled = true;window.ambflipPageSizes = {portrait:{ width:"+ _screenWidth +",height:"+  _screenHeight +"},landscape:{width: "+ _screenHeight +",height: "+  _screenWidth +"}};window.ambflipSocialBarHeight = 60.0;window.ambflipOrientation = 0;ambflipPrintSize=\"normal\";");
		webView.loadUrl("javascript:window.ambflipArticleMarkup='" + content + "';");
		webView.loadUrl("javascript:window.ambtml='" + tmpl + "';");
		webView.loadUrl("javascript:window.fontSize='" +fontsize+ "';");
		webView.loadUrl("javascript:window.formFactor='phone';");
		
		webView.loadUrl(load_path);		
		//webView.loadData(content, "text/html", "UTF-8");
		
		//TRACKING USER PAPER CLICK
		EasyTracker.getInstance().setContext(GlobalApplication._());			
	    Tracker tracker = EasyTracker.getTracker();
		tracker.sendEvent(Contants.TRACKER_DETAIL_BUTTONS,id + "-" + Contants.TRACKER_ACTIONS_CLICKED,article.getTitle() , Utils.currentMillis());
		
		// keep device awake
		//pm = (PowerManager) getSystemService(POWER_SERVICE);
		//wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "wakelock");
		// This will make the screen and power stay on
		// This will release the wakelook after 1000 ms
		//wakeLock.acquire(600000);
		 
		// Alternative you can request and / or  release the wakelook via:
		// wakeLock.acquire(); wakeLock.release();
		
	}
	String oneline(String multiline) {
	    String[] lines = multiline.split(System.getProperty("line.separator"));
	    StringBuilder builder = new StringBuilder();
	    builder.ensureCapacity(multiline.length()); // prevent resizing
	    for(String line : lines) builder.append(line);
	    return lines.toString();
	}
		
	
	@SuppressWarnings("deprecation")
	public void increaseFont(View v)
	{
		WebSettings settings = webView.getSettings();
		if(_isFontChange == 0)
		{
			_isFontChange = 1;
			settings.setTextZoom( (int)(settings.getTextZoom() * 1.3) );
			settings.setTextSize(WebSettings.TextSize.LARGER);
			
			//webView.loadUrl("javascript:window.ambflipNativeFlip = true;window.isAndroid = true;window.ambflipMagazine = true;window.ambflipBridgeEnabled = true;window.ambflipShowImageEnabled = true;window.ambflipPageSizes = {portrait:{ width:"+ _screenWidth +",height:"+  _screenHeight +"},landscape:{width: "+ _screenHeight +",height: "+  _screenWidth +"}};window.ambflipSocialBarHeight = 60.0;window.ambflipOrientation = 0;ambflipPrintSize=\"normal\";");
			//webView.loadUrl("javascript:window.ambflipArticleMarkup='" + content + "';");		
			//webView.loadUrl(load_path);
		}
		else
		{
			settings.setTextSize(WebSettings.TextSize.NORMAL);
			_isFontChange = 0;
			
			//webView.loadUrl("javascript:window.ambflipNativeFlip = true;window.isAndroid = true;window.ambflipMagazine = true;window.ambflipBridgeEnabled = true;window.ambflipShowImageEnabled = true;window.ambflipPageSizes = {portrait:{ width:"+ _screenWidth +",height:"+  _screenHeight +"},landscape:{width: "+ _screenHeight +",height: "+  _screenWidth +"}};window.ambflipSocialBarHeight = 60.0;window.ambflipOrientation = 0;ambflipPrintSize=\"normal\";");
			//webView.loadUrl("javascript:window.ambflipArticleMarkup='" + content + "';");		
			//webView.loadUrl(load_path);
		}
        
	}
	
	
	public void onShareAction(View v)
	{
		Intent intent=new Intent(android.content.Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

		// Add data to the intent, the receiving app will decide what to do with it.
		intent.putExtra(Intent.EXTRA_SUBJECT,article.getTitle());
		intent.putExtra(Intent.EXTRA_TEXT, article.getUrl() );
		startActivity(Intent.createChooser(intent,"Chia sẻ"));
	}

}
